package com.zijie.members.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zijie.members.mapper.MemberAddressMapper;
import com.zijie.members.mapper.MemberMapper;
import com.zijie.members.model.Members;
import com.zijie.members.model.search.MemberSearchBean;
import com.zijie.members.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class MemberServiceImpl implements MemberService {
    //依赖注入：
    private MemberMapper memberMapper;
    private MemberAddressMapper memberAddressMapper;

    @Autowired
    public void setMemberAddressMapper(MemberAddressMapper memberAddressMapper) {
        this.memberAddressMapper = memberAddressMapper;
    }

    @Autowired
    public void setMemberMapper(MemberMapper memberMapper) {
        this.memberMapper = memberMapper;
    }


    //查询全部会员
    @Override
    public Page<Members> findAll(Page<Members> page, MemberSearchBean memberSearchBean) {
        return memberMapper.findAll(page, memberSearchBean);
    }

    //根据id删除单个会员
    @Override
    public int deleteById(Integer id) {
        memberAddressMapper.deleteByMemberId(id);
        return memberMapper.deleteById(id);
    }

    @Override
    public Members findById(Integer id) {
        return memberMapper.selectById(id);
    }

    @Transactional
    @Override
    public boolean save(Members members) {
        memberMapper.insert(members);
//        Integer id = members.getId();
//        System.out.println("id============================"+ id);

        return   memberAddressMapper.insertByMenber(members)>0;
    }

    @Override
    public boolean update(Members members) {
        Integer id = members.getId();//获取会员id
        //id在地址表中是否存在
        int count = memberAddressMapper.eqByMemberId(id);
        if (count>0){
            memberAddressMapper.updateByMember(members);
        } else if (count==0) {
            memberAddressMapper.insertByMenber(members);
        }

        return memberMapper.updateById(members) == 1;
    }

    @Transactional
    @Override
    public int deleteAll(List<Integer> ids) {
        memberAddressMapper.deleteByMemberIds(ids);
        return memberMapper.deleteByIds(ids);
    }

    //更新会员的启用状态：
    @Override
    public boolean updateEnabled(Integer id, Boolean enabled) {
        return memberMapper.update(id, enabled);
    }

    @Override
    public Members findByPhone(String phone) {
        return memberMapper.findByPhone(phone);
    }
}
